# -*- coding:utf-8 -*-
import requests, sys
from bs4 import BeautifulSoup

class downloader(object):
	def __init__(self):
		self.server = 'http://www.biqukan.com'
		self.target = 'http://www.biqukan.com/1_1094/'
		self.names = []
		self.urls = []
		self.nums = []
		

	def getNamesAndUrls(self):
		req = requests.get(self.target)
		html = req.text
		div_bf = BeautifulSoup(html, 'html.parser')
		div = div_bf.find_all('div', class_ = 'listmain')
		# print(div[0])
		a_bf = BeautifulSoup(str(div[0]))
		a = a_bf.find_all('a')
		self.nums = len(a[15:])
		for each in a[15:]:
			self.names.append(each.string)
			self.urls.append(self.server + each.get('href'))
			# print(each.string, server + each.get('href'))
	
	# 调用处只传了一个参数，为何这里需要两个形参，没有两个还会报错
	def getContent(url, target):
		response = requests.get(url = target);
		html = response.text
		bf = BeautifulSoup(html, 'html.parser')
		texts = bf.find_all('div', class_ =  'showtxt')
		text = texts[0].text.replace('\xa0'*8, '\n\n')
		# print(text)
		return text
		
	def saveFile(self, name, path, text):
		save_flag = True
		with open(path, 'a', encoding = 'utf-8') as f:
			f.write(name + '\n')
			f.writelines(text)
			f.write('\n\n')
			
if __name__ == '__main__':
	dl = downloader()
	dl.getNamesAndUrls()
	print('《一念永恒》开始下载……')
	for i in range(dl.nums):
		# print(dl.names[i] + dl.urls[i])
		dl.saveFile(dl.names[i], '一念永恒.txt', dl.getContent(dl.urls[i]))
		sys.stdout.write('已下载：%.3f%%' % float(i / dl.nums) + '\r')
		sys.stdout.flush()
	print('下载完成')

# 问题：
# 1、第一章重复
#		